/* eslint-disable no-plusplus,import/no-extraneous-dependencies */
const eventClass = require('./eventClass');

const spawn = eval('require')('child_process').spawn;

function Uint8ArrayToString(fileData) {
    let dataString = '';
    for (let i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }

    return dataString;
}
class spawnClass extends eventClass {
    constructor() {
        super('spawnClass');
        this.iconv = eval('require')('iconv-lite');
        this.encoding = 'cp936';
    }

    toBuffer(ab) {
        const buf = new Buffer(ab.byteLength);
        const view = new Uint8Array(ab);
        for (let i = 0; i < buf.length; ++i) {
            buf[i] = view[i];
        }
        return buf;
    }
    toCp936(data) {
        return this.iconv.decode(this.toBuffer(data), this.encoding);
    }

    runCommand(cb, { command, args }) {
        const cmd = spawn(command, (args instanceof Array) ? args : [args], {
            shell: true,
        });

        cmd.stdout.on('data', (data) => {
            this.returnMethod(cb, {
                data: {
                    type: 'stdout',
                    data: this.toCp936(data),
                },
            });
        });

        cmd.stderr.on('data', (data) => {
            this.returnMethod(cb, {
                data: {
                    type: 'stderr',
                    data: this.toCp936(data),
                },
            });
        });

        cmd.on('close', (code) => {
            this.returnMethod(cb, {
                data: {
                    type: 'close',
                    data: code,
                },
            });
        });

        this.returnMethod(cb, {
            data: {
                type: 'pid',
                data: cmd.pid,
            },
        });
    }
}

module.exports = spawnClass;
/**
 * 测试
 * window.c = 0;
 * function mdiv(content) {
 *      var div = document.createElement('div');
 *      div.innerText = content;
 *      document.body.append(div)
 *      div.style.position = 'absolute';
 *      div.style.top = (c * 40) + 'px';
 *      div.style.left = '0px';
 *      div.style.lineHeight = '20px';
 *      div.style.fontSize = '20px';
 *      window.c ++;
 * }
 * rc = Object.assign({},fetchEvent.fetchEventAction.spawn.runCommand);
 * rc.param.command = 'cmd';
 * rc.param.args = ['/k','dir'];
 * window.rcRet = [];
 * fetchEvent.fetchEventApi(rc,function(a) {
 *      rcRet.push(a);
 *      mdiv(a.data.type + ':' + a.data.data)
 * });
* */

